<?php

namespace App;

use App\Models\AdminUser;
use App\Models\Department;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Patent extends BaseModel
{
    protected $guarded = ['id', 'created_at', 'updated_at'];
    protected $casts = [
        'sale_mode'  => 'json',
        'assessment' => 'json',
    ];

    public function apply(): BelongsTo
    {
        return $this->belongsTo(PatentApply::class, 'patent_apply_id');
    }

    //专利费用
    public function fees(): HasMany
    {
        return $this->hasMany(PatentFee::class, 'patent_sn', 'patent_sn');
    }

    public function department(): BelongsTo
    {
        return $this->belongsTo(Department::class, 'department_id');
    }

    public function unpaid()
    {
        return $this->fees->where('state', 0);
    }

    public function paid()
    {
        return $this->fees->where('state', 1);
    }

    public function user()
    {
        return $this->belongsTo(AdminUser::class, 'user_id');
    }

    public function transaction()
    {
        return $this->hasOne(Transaction::class, 'patent_sn', 'patent_sn');
    }

    public static function boot()
    {
        parent::boot(); // TODO: Change the autogenerated stub

        static::deleting(function ($model) {

        });
        static::updating(function ($model) {

        });
    }

    public function addSale(array $data)
    {
        $patent_sn = $this->patent_sn;
        $this->transaction()->updateOrCreate(['patent_sn' => $patent_sn], [
            'user_id'        => $this->user_id,
            'department_id'  => $this->department_id,
            'patent_name'    => $this->patent_name,
            'patent_sn'      => $patent_sn,
            'patent_type_id' => $this->patent_type_id,
            'buyer'          => data_get($data, 'buyer'),
            'amount'         => data_get($data, 'amount'),
            'type'           => data_get($data, 'type'),
            'date'           => data_get($data, 'date'),
            'contact_person' => data_get($data, 'contact_person'),
            'contact_mobile' => data_get($data, 'contact_mobile'),
        ]);
        $this->state = 2;
        $this->save();
        $this->apply()->update(['status' => 2]);
    }

}
